const koa=require('koa');
const db=require('./libs/mysql');
const router=require('koa-router');
const url=require('url')
const regs=require('./libs/regs.js');
const mysql=require('mysql');




//1.创建服务器，使koa连接socket.io
let app=new koa();

const server = require('http').createServer(app.callback())
server.listen(8081);

const wsServer = require('socket.io')(server);

let r1=new router();
app.use(r1.routes());

//跨域:koa没有跨域
r1.use(async (ctx,next)=>{
	if(ctx.request.headers['origin']&& url.parse(ctx.request.headers['origin']).hostname=='localhost'){
		ctx.set('Access-Control-Allow-Origin','*');//设置跨域的头
	}
	await next();
})

	let aSock=[];
	let asokect={};
	wsServer.on('connection', sock=>{//创建对话连接
		console.log('连接成功');
		aSock.push(sock)
		console.log(aSock.length)
		let cur_username='';
		let cur_userID=0;
		let otherName="" ;
		let uName="";
		let oName="";

	//2.登录
	sock.on('login',(user,pass)=>{
		console.log('登录')

		//1.校验数据
		if(!regs.username.test(user)){
			sock.emit('login_ret',1,'用户不符合规范');
			console.log('登录1')
		}else if(!regs.password.test(pass)){
			sock.emit('login_ret',1,'密码不符合规范');
			console.log('登录2')
		}else{
			console.log('登录3')
			//2.用户名是否存在
			async function asy(){//封装async函数
				//获取数据
			let data=await db.query(`SELECT ID,password FROM qqcopy WHERE username='${user}'`)
				
				if(data.err){
					sock.emit('login_ret',1,'数据库3有问题');
					console.log(err)
				}else if(data.length==0){
					console.log('ssss')
					sock.emit('login_ret',1,'用户名或密码有错');
				}else{
					//3.改在线状态
					let datas=await db.query(`UPDATE qqcopy SET online=1 WHERE ID=${data[0].ID}`)
						if(datas.err){
							sock.emit('login_ret', 1 ,'数据库4有错误');
						}else{
							sock.emit('login_ret', 0 ,'登录成功');
							cur_username=user;
							cur_userID=data[0].ID;
							asokect[cur_username]=sock;
						}
					}
					}
					asy();
				}
		})


	//获取对话对象
	sock.on('withSpeak',(uNames,oNames)=>{
		uName=uNames
		oName=oNames;
		console.log(uName,oName)
	})


	//3.发言
	sock.on('msgData',txt=>{
		if(!txt){
			sock.emit('msg_ret',1,'消息不能为空')
		}else{
			console.log(txt);
			if(oName!="broadcasts"){//私聊时，利用name与oName判断出聊天对象
				for ( let name in asokect){
					if(name!=cur_username&&name==oName){
						asokect[name].emit('broadcastMsg',cur_username,txt)
					}
				}
			}else{
				//群聊，多人聊天，借用socket.io的广播功能
				sock.broadcast.emit("broadcastMsg",cur_username,txt);
			}
			sock.emit('msg_ret',0,txt)
		}
	})


})

r1.get('/house/:username',async ctx=>{

	//获取house数据，对应的username获取对应的数据
	let {username}=ctx.params;

	let data=await db.query(`SELECT * FROM qqcopy WHERE username='${username}'`);

	if(data.length==0){//返回给前台的主体
		ctx.response.body={err:true,data:null};
	}else{
		ctx.response.body={err:false,data:data[0]};

	}
})
